package com.drojian.serviceclient;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.drojian.demo3.service.remote.IStudentService;
import com.drojian.demo3.service.remote.Student;

public class MainActivity extends AppCompatActivity {
    private Button bind_remote_service,user_remote_service,unbind_remote_service;
    private EditText edit_remote_service;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        edit_remote_service = findViewById(R.id.edit_remote_service);
    }
        private ServiceConnection conn;
        private IStudentService studentService;
        public void BindRemoteService(View view) {
            if(conn == null){
                Intent intent = new Intent("com.drojian.demo3.service.MyRemoteServic.action");
                intent.putExtra("id",edit_remote_service.getText());
                conn = new ServiceConnection() {
                    @Override
                    public void onServiceConnected(ComponentName name, IBinder service) {
                        Log.d("xjq", "onServiceConnected() ");
                        studentService = IStudentService.Stub.asInterface(service);
                    }

                    @Override
                    public void onServiceDisconnected(ComponentName name) {

                    }
                };
                bindService(intent,conn, Context.BIND_AUTO_CREATE);
            }else {
                Toast.makeText(this,"已经进行绑定",Toast.LENGTH_SHORT).show();
            }
        }

        public void invokeService(View view) throws RemoteException {
            if(studentService!= null){
                int id = Integer.parseInt(edit_remote_service.getText().toString());
                Student student = studentService.getStudentById(id);
                Toast.makeText(this,student.toString(),Toast.LENGTH_SHORT).show();
            }
        }

        public void unBindRemoteService(View view) {
            if(conn != null){
                unbindService(conn);
                conn = null;
                studentService = null;
                Toast.makeText(this,"解绑成功",Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(this,"未进行绑定",Toast.LENGTH_SHORT).show();

            }
        }
    }